package com.freshSystem.gateway.config;

import com.alibaba.fastjson.JSONObject;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import util.JWTUtil;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * The type Api gateway config.
 */
@Component
public class ApiGatewayConfig implements GlobalFilter, Ordered {
    /**
     * The Jwt util.
     */
    @Autowired
    private JWTUtil jwtUtil;
    /**
     * The Logger.
     */
    private Logger logger = Logger.getLogger(this.getClass());
    /**
     * The Skip urls.
     */
    private String[] skipUrls = {"/login", "/register", "/download", "/upload"};

    /**
     * Filter mono.
     *
     * @param exchange the exchange
     * @param chain    the chain
     * @return the mono
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("开启token验证");
        JSONObject msg = new JSONObject();
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String method = request.getMethod().toString();
        String path = request.getURI().getPath();
        logger.info("请求路径: {}" + path);
        //跳过不需要验证的路径，该路径写在了配置文件中
        if (null != skipUrls && Arrays.asList(skipUrls).contains(path)) {
            return chain.filter(exchange);
        }
        if ("options".equalsIgnoreCase(method)) {
            return chain.filter(exchange);
        }
        String authorization = request.getHeaders().getFirst("Authorization");
        logger.info("token:" + authorization);
        if (StringUtils.isEmpty(authorization)) {
            msg.put("code", StatusCode.ACCESSERROR);
            msg.put("message", "token为空");
            byte[] bits = msg.toJSONString().getBytes(StandardCharsets.UTF_8);
//            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //指定编码
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//            return response.writeWith(Mono.just(buffer));
            return response.setComplete();
        }
        try {
            Claims claims = jwtUtil.parseJWT(authorization);
            if (claims.isEmpty()) {
                logger.debug("token失效了");
                msg.put("code", StatusCode.ERROR);
                msg.put("message", "token失效");
                byte[] bits = msg.toJSONString().getBytes(StandardCharsets.UTF_8);
//                DataBuffer buffer = response.bufferFactory().wrap(bits);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//                return response.writeWith(Mono.just(buffer));
                return response.setComplete();
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("token失效");
            msg.put("code", StatusCode.ERROR);
            msg.put("message", "token失效");
            byte[] bits = msg.toJSONString().getBytes(StandardCharsets.UTF_8);
//            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "text/plain;charset=UTF-8");
//            return response.writeWith(Mono.just(buffer));
            return response.setComplete();
        }

        return chain.filter(exchange);
    }

    /**
     * Gets order.
     *
     * @return the order
     */
    @Override
    public int getOrder() {
        System.out.println("springboot aaa---------------");
        return 1;
    }
}
